package com.foreveross.util.redis;

import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;

import org.apache.commons.lang3.SerializationUtils;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * 封装对对象的序列化，大部分用apache来实现
 * 字符串用类似spring的string序列化做法，UTF-8编码
 *
 * @author Administrator
 */
public class RedisSerializeUtil {

    private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ProxyIpJedisTools.class);
    private static ObjectMapper objectMapper = new ObjectMapper();

//    public static String serializeProxyIpModel(ProxyIpModel obj) {
//        try {
//            return objectMapper.writeValueAsString(obj);
//        } catch (IOException e) {
//            log.error(e);
//            e.printStackTrace();
//        }
//        return null;
//    }

//    public static ProxyIpModel deserializeProxyIpModel(String str) {
//        try {
//            return objectMapper.readValue(str, ProxyIpModel.class);
//        } catch (IOException e) {
//            log.error(e);
//            e.printStackTrace();
//        }
//        return null;
//    }

    public static byte[] serializeObject(Serializable obj) {
        return SerializationUtils.serialize(obj);
    }

    public static byte[] serializeString(String str) {
        return str == null ? null : str.getBytes(getCharset());
    }

    public static Object deserializeObject(byte[] b) {
        return SerializationUtils.deserialize(b);
    }

    @SuppressWarnings("unchecked")
    public static <T> T deserializeObject(byte[] b, Class<T> clzz) {
        return (T) SerializationUtils.deserialize(b);
    }

    public static String deserializeString(byte[] b) {
        return b == null ? null : new String(b, getCharset());
    }

    private static Charset getCharset() {
        return Charset.forName("UTF8");
    }


}
